package com.hoperun.common.util;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.converters.DoubleConverter;
import org.apache.commons.beanutils.converters.FloatConverter;
import org.apache.commons.beanutils.converters.IntegerConverter;
import org.apache.commons.beanutils.converters.ShortConverter;

/**
 * User: Sharper
 * Date: 2006-7-24
 * Time: 23:08:55
 */
public final class ObjectUtil
{
	static
	{
		ConvertUtils.register(new DateConverter(), java.util.Date.class);
		ConvertUtils.deregister(Integer.class);
		ConvertUtils.deregister(Double.class);
		ConvertUtils.deregister(Float.class);
		ConvertUtils.deregister(Short.class);
		//
		ConvertUtils.register(new IntegerConverter(null),Integer.class);
		ConvertUtils.register(new DoubleConverter(null),Double.class);
		ConvertUtils.register(new FloatConverter(null),Float.class);
		ConvertUtils.register(new ShortConverter(null),Short.class);
	}	
	
    /**
     * @param s
     * @return 
     */
    public static boolean isNullOrEmpty(String s)
    {
        return s == null || s.length() == 0;
    }

    /**
     * 
     * @param objects
     * @return 
     */
    public static boolean isNullOrEmpty(Object[] objects)
    {
        return objects == null || objects.length == 0;
    }

    /**
     * 
     * @param className
     * @return
     * @throws Exception
     */
    public static Object newInstance(String className) throws Exception
    {
        if(isNullOrEmpty(className))
        {
            throw new Exception("argument className null or Empty.");
        }
        //
        try
        {
            return newInstance(Class.forName(className));

        }catch(Exception ex)
        {
            throw ex;
        }
    }

    /**
     * 
     * @param cls
     * @return
     * @throws Exception
     */
    public static Object newInstance(Class cls) throws Exception
    {
          if(cls == null)
          {
              throw new Exception("argument cls null.");
          }
          try
          {
             return cls.newInstance();

          }catch(Exception ex)
          {
              throw ex;
          }
    }

    /**
     * 
     * @param cls
     * @param propNames 
     * @param propValues 
     * @return
     * @throws Exception
     */
    public static Object populateObject(Class cls,String[] propNames, Object[] propValues) throws Exception
    {
        Object instance = newInstance(cls);
        //
        if(isNullOrEmpty(propNames) || isNullOrEmpty(propValues))
        {
            return instance;
        }
        //
        int len = Math.min(propNames.length, propValues.length);
        for(int i = 0 ; i < len ; i ++ )
        {
            try
            {
                BeanUtils.setProperty(instance,propNames[i],propValues[i]);

            }catch(Exception ex)
            {
                ex.printStackTrace();
            }
        }
        //
        return instance;
    }

    /**
     * 
     * @param instance
     * @param propName
     * @param propValue
     * @return
     * @throws Exception
     */
    public static Object  setProperty(Object instance,String propName,Object propValue) throws Exception
    {
        try
        {
            BeanUtils.setProperty(instance, propName,propValue);

        }catch(Exception ex)
        {
            throw ex;
        }
        return instance;
    }

    /**
     * 
     * @param cls
     * @param propKeyPrefix - 
     * @param parameters
     * @return
     * @throws Exception
     */
    public static Object populateObject(Class cls, String propKeyPrefix, Map parameters) throws Exception
    {
        Object instance = newInstance(cls);
        //
        if(parameters == null || parameters.isEmpty())
        {
            return instance;
        }
        //---------------------------------------------------------
     
        Map properties = isNullOrEmpty(propKeyPrefix)? parameters : new HashMap();
        //
        if(properties.isEmpty())
        {
            Iterator itor1 = parameters.keySet().iterator();
            while(itor1.hasNext())
            {
                String key = (String)itor1.next();
                String _key = key.toLowerCase();
                if(_key.startsWith(propKeyPrefix.toLowerCase()))
                {
                    //
                   _key = key.substring(propKeyPrefix.length()+1);
                    //
                   properties.put(_key,parameters.get(key));
                   //                  
                }
            }
        }
        //
        if(properties.isEmpty())
        {
            return instance;
        } 
        //
        try
        {     
        	
            BeanUtils.populate(instance, properties);

        }catch(Exception ex)
        {
            throw ex;
        }
        //
        return instance;
    }
    
    /*
	 * 
	 * 
	 */
	public static String replace(String strSource, String strFrom, String strTo) 
	{
		
		//
		if (strFrom == null || strFrom.equals(""))
		{
			return strSource;
		}
		//
		String strDest = "";
		// 
		int intFromLen = strFrom.length();
		int intPos;
		// 
		while ((intPos = strSource.indexOf(strFrom)) != -1) 
		{
			// 
			strDest = strDest + strSource.substring(0, intPos);
			// 
			strDest = strDest + strTo;
			// 
			strSource = strSource.substring(intPos + intFromLen);
		}
		// 
		strDest = strDest + strSource;
		return strDest;
	}	
	
	/**
	 * 将字符串数组转换为Integer[]
	 * @param values
	 * @return
	 */
	public static Integer[] convert(String[] values)
	{
		if(isNullOrEmpty(values))
		{
			return new Integer[0];
		}
		//int j = 0;
		java.util.ArrayList al = new java.util.ArrayList();
		for(int i = 0 ;i < values.length ; i ++)
		{
			try
			{
				al.add( Integer.valueOf(values[i]));
				
			}catch(Exception ex)
			{
				ex.printStackTrace();
			}
		}
		//
		return (Integer[])al.toArray(new Integer[al.size()]);
	}
	
	
	/**
	 * @return
	 */
	public static String format(String fmt,Object[] params)
	{
		if(isNullOrEmpty(fmt))
    	{
    		return "";
    	}
    	//
    	if(isNullOrEmpty(params))
    	{
    		return fmt;
    	}
       	//
    	//StringBuffer s = new StringBuffer();
    	for(int i = 0 ; params != null && i < params.length; i ++)
    	{
    		String s0 = params[i]== null ? "null" : params[i].toString();
    		fmt = replace(fmt,"{"+i+"}",s0);
    	}
    	//
    	return fmt;
	}
	
	/**========================================================================**/
	private static Object _isNull(Object var, Object nullreplace)
	{
		return var == null ? nullreplace : var;
	}
	
	public static Integer isNull(Integer var, Integer nullreplace)
	{
		return (Integer)_isNull(var,nullreplace);
	}
	
	public static String isNull(String var, String nullreplace)
	{
		return (String)_isNull(var,nullreplace);
	}
	
	public static Double isNull(Double var, Double nullreplace)
	{
		return (Double)_isNull(var,nullreplace);
	}
	
	public static Long isNull(Long var, Long nullreplace)
	{
		return (Long)_isNull(var,nullreplace);
	}
	
	public static Short isNull(Short var, Short nullreplace)
	{
		return (Short)_isNull(var,nullreplace);
	}
	
	public static Date isNull(Date var, Date nullreplace)
	{
		return (Date)_isNull(var,nullreplace);
	}	
	/**========================================================================**/
	
	/**
	 * 获取季度 1,2,3,4
	 * @param c 若为null, 则返回当前日期的季度
	 */
	public static int getQuarter(Calendar c)
	{
		if(c == null)
		{
			c = Calendar.getInstance();
		}
		//
		int month = c.get(Calendar.MONTH) + 1; /*1,2,....12*/
		if(month <= 3) return 1;
		if(month <= 6) return 2;
		if(month <= 9) return 3;
		//
		return 4;
	}
}
